package com.gitee.booting.idem4j.autoconfigure;

import com.gitee.booting.idem4j.Idem4jFilter;
import com.gitee.booting.idem4j.properties.Idem4jProperties;
import com.gitee.booting.idem4j.util.JavaUtils;
import org.springframework.boot.context.properties.ConfigurationPropertiesBinding;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.function.Supplier;

@Order
@Configuration
public class Idem4jAutoConfiguration {

    @Bean
    public Idem4jProperties idem4jProperties() {
        return new Idem4jProperties();
    }

    @Bean
    public Idem4jFilter idem4jFilter(RequestMappingHandlerMapping mapping,
                                     Idem4jProperties properties,
                                     RedisTemplate<Object, Object> template) {
        return new Idem4jFilter(mapping, properties, template);
    }

    /**
     * Remove parameterized type for backward capability, see {@link FilterRegistrationBean}
     * @param filter An instance of {@link Idem4jFilter}
     * @return new {@link FilterRegistrationBean}
     */
    @Bean
    public FilterRegistrationBean idem4jFilterRegistration(Idem4jFilter filter) {
        return new FilterRegistrationBean(filter);
    }

    @Bean
    @ConfigurationPropertiesBinding
    public Converter<String, Supplier<String>> stringToSupplier() {
        return new StringToSupplier();
    }


    public static class StringToSupplier implements Converter<String, Supplier<String>> {
        @Override
        public Supplier<String> convert(String source) {
            return JavaUtils.build(source);
        }
    }
}
